package cn.lyjuan.dwz_manage.core.java.service;


import cn.lyjuan.dwz_manage.core.base.pojo.ManagePojo;
import cn.lyjuan.dwz_manage.core.base.pojo.RolePojo;
import cn.lyjuan.dwz_manage.core.java.dto.QueryResultBean;
import cn.lyjuan.dwz_manage.core.java.exception.DwzManageException;
import cn.lyjuan.dwz_manage.core.java.mapper.IMgManageMapper;
import cn.lyjuan.dwz_manage.core.java.mapper.IMgManageRoleMapper;
import cn.lyjuan.dwz_manage.core.java.util.SuperAdminUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PostAuthorize;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * Created by ly on 2015/1/9.
 */
@Service("mgManageService")
public class ManageService
{
    private static Logger log = LogManager.getLogger(ManageService.class.getName());

    @Autowired
    private IMgManageMapper manageMapper;

    @Autowired
    private IMgManageRoleMapper manageRoleMapper;

    /**
     * 查看管理员创建的管理员
     *
     * @param manage
     * @return
     */
    public QueryResultBean<ManagePojo> queryManages(ManagePojo manage, Map<String, String> param, int pn, int ps)
    {
        QueryResultBean<ManagePojo> bean = new QueryResultBean<>();
        List<ManagePojo> list = null;
        int totalCount = -1;
        if (SuperAdminUtils.isSuperManager(manage.getCreateby()))// 超级管理员可以查看所有权限
        {
            list = manageMapper.selectAllManages(param, (pn - 1) * ps, ps);
            totalCount = manageMapper.selectAllManageCount(param);
        }
        else
        {
            list = manageMapper.selectManagesForCreater(manage.getName(), param, (pn - 1) * ps, ps);
            totalCount = manageMapper.selectManageCountForCreater(manage.getName(), param);
        }

        bean.setList(list);
        bean.setTotalCount(totalCount);

        return bean;
    }

    /**
     * 添加管理员
     *
     * @param creater 创建者信息
     * @param manage
     * @return
     */
    public ManagePojo addManage(ManagePojo creater, ManagePojo manage)
    {
        manage.setName(manage.getName().trim());// 去首尾空格

        // 判断该账号是否存在
        ManagePojo manageExist = manageMapper.selectByName(manage.getName());
        if (null != manageExist)
            throw new DwzManageException("账号已存在");

        manage.setCreateby(creater.getName());
        manage.setCreatetime(new Date());
        manage.setLastmodifypwdtime(new Date());

        manageMapper.insert(manage);

        return manage;
    }

    /**
     * 更新管理员信息
     * @param fromManage    被修改用户，修改前的信息
     * @param toManage      被修改用户，修改后信息
     */
    @PostAuthorize("#fromManage.createby == principal.username" +// 当前用户创建的用户
            " or #fromManage.name == principal.username")// 当前用户
    public void saveManage(ManagePojo fromManage, ManagePojo toManage)
    {
        if (!fromManage.getPwd().equals(toManage.getPwd()))// 修改了密码
            toManage.setLastmodifypwdtime(new Date());

        toManage.setId(fromManage.getId());
        toManage.setName(null);// 不可修改账号

        manageMapper.updateById(toManage);
    }

    /**
     * 根据账号查询管理员
     * @param name
     * @return
     */
    @PostAuthorize("returnObject.name == principal.username" +// 当前用户
            " or returnObject.createby == principal.username")// 被当前用户创建的用户
    public ManagePojo queryManageByName(String name)
    {
        return manageMapper.selectByName(name);
    }

    /**
     * 给用户{@code user}关联角色{@code roleIds}
     * @param manage
     * @param hadRoles      有权限的角色
     * @param user
     * @param roleIds       未包含其中的已关联角色将被取消；包含在其中的未关联角色将被关联
     */
    public void relateRole(ManagePojo manage, List<RolePojo> hadRoles, ManagePojo user, Integer[] roleIds)
    {
        // 判断所有角色是否均有权限操作
        if (null == hadRoles || hadRoles.isEmpty())
            throw new DwzManageException("当前无任何角色权限");

        if (null != roleIds)
        {
            // 去重
            Set<Integer> set = new HashSet<>(roleIds.length);
            set.addAll(Arrays.asList(roleIds));
            roleIds = set.toArray(new Integer[set.size()]);

            // 判断是否所有角色都有权限操作
            boolean hasRole;
            for (Integer d : roleIds)
            {
                if (null == d || d < 1)
                    throw new DwzManageException("角色参数不合法");
                hasRole = false;// 初始化控制
                for (RolePojo r : hadRoles)
                {
                    if (d == r.getId())
                    {
                        hasRole = true;
                        break;
                    }
                }
                if (!hasRole)// 角色无权限操作
                {
                    log.info("[{}] 无权限操作 [{}]角色", manage.getName(), d);
                    throw new DwzManageException("角色无权限");
                }
            }
        }

        // 删除取消的
        int delCount = manageRoleMapper.deleteNotInRoles(user.getId(), roleIds);

        // 添加未关联的
        if (null != roleIds && roleIds.length > 0)
        {
            int addCount = manageRoleMapper.insertNotExistRoles(manage.getName(), user.getId(), roleIds);
        }
    }
}
